<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
    <link rel="stylesheet" th:href="@{/webjars/bootstrap/5.1.3/css/bootstrap.min.css}">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    <style>
        .sidebar {
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            z-index: 100;
            padding: 48px 0 0;
            box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
            background-color: #f8f9fa;
            width: 250px;
        }
        
        .main-content {
            margin-left: 250px;
            padding: 20px;
            margin-top: 56px;
        }
        
        .nav-link {
            color: #333;
            padding: 0.8rem 1rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .nav-link:hover {
            background-color: #e9ecef;
        }
        
        .nav-link.active {
            color: #fff;
            background-color: #0d6efd;
        }
        
        .table-actions {
            white-space: nowrap;
        }
        
        .search-box {
            max-width: 300px;
        }
    </style>
    <script th:src="@{/webjars/bootstrap/5.1.3/js/bootstrap.bundle.min.js}"></script>
    <script th:src="@{/webjars/jquery/3.6.0/jquery.min.js}"></script>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-dark bg-primary fixed-top">
        <div class="container-fluid">
            <a class="navbar-brand" th:href="@{/}">
                <i class="bi bi-building"></i>
                管理系统
            </a>
            <div class="d-flex align-items-center">
                <span class="navbar-text me-3">
                    <i class="bi bi-person-circle"></i>
                    欢迎使用
                </span>
            </div>
        </div>
    </nav>

    <!-- 侧边栏 -->
    <nav class="sidebar">
        <div class="position-sticky">
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link" th:href="@{/}">
                        <i class="bi bi-house-door"></i>
                        首页
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" th:href="@{/user/list}">
                        <i class="bi bi-people"></i>
                        用户管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" th:href="@{/role/list}">
                        <i class="bi bi-person-badge"></i>
                        角色管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" th:href="@{/department/list}">
                        <i class="bi bi-diagram-3"></i>
                        部门管理
                    </a>
                </li>
            </ul>
        </div>
    </nav>

    <!-- 主要内容区域 -->
    <main class="main-content">
        <div class="container-fluid">
            <!-- 标题和添加按钮 -->
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="bi bi-people"></i> 用户管理</h2>
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUserModal">
                    <i class="bi bi-plus-circle"></i> 添加用户
                </button>
            </div>

            <!-- 搜索框 -->
            <div class="card mb-4">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col-auto">
                            <div class="input-group search-box">
                                <input type="text" id="searchInput" class="form-control" placeholder="搜索用户...">
                                <button class="btn btn-outline-primary" type="button" onclick="searchUsers()">
                                    <i class="bi bi-search"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 用户列表 -->
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th>ID</th>
                                    <th>用户名</th>
                                    <th>姓名</th>
                                    <th>邮箱</th>
                                    <th>电话</th>
                                    <th>创建时间</th>
                                    <th class="text-center">操作</th>
                                </tr>
                            </thead>
                            <tbody id="userTableBody">
                                <!-- 用户数据将通过 JavaScript 动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 添加用户模态框 -->
    <div class="modal fade" id="addUserModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-person-plus"></i> 添加用户</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addUserForm" class="needs-validation" novalidate>
                        <div class="mb-3">
                            <label class="form-label">用户名</label>
                            <input type="text" class="form-control" name="username" required>
                            <div class="invalid-feedback">请输入用户名</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">密码</label>
                            <input type="password" class="form-control" name="password" required>
                            <div class="invalid-feedback">请输入密码</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">姓名</label>
                            <input type="text" class="form-control" name="realName">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">邮箱</label>
                            <input type="email" class="form-control" name="email">
                            <div class="invalid-feedback">请输入有效的邮箱地址</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">电话</label>
                            <input type="tel" class="form-control" name="phone">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addUser()">
                        <i class="bi bi-save"></i> 保存
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑用户模态框 -->
    <div class="modal fade" id="editUserModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-pencil-square"></i> 编辑用户</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editUserForm" class="needs-validation" novalidate>
                        <input type="hidden" name="id">
                        <div class="mb-3">
                            <label class="form-label">用户名</label>
                            <input type="text" class="form-control" name="username" required>
                            <div class="invalid-feedback">请输入用户名</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">姓名</label>
                            <input type="text" class="form-control" name="realName">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">邮箱</label>
                            <input type="email" class="form-control" name="email">
                            <div class="invalid-feedback">请输入有效的邮箱地址</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">电话</label>
                            <input type="tel" class="form-control" name="phone">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="updateUser()">
                        <i class="bi bi-save"></i> 保存
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script th:src="@{/webjars/bootstrap/5.1.3/js/bootstrap.bundle.min.js}"></script>
    <script>
        // 页面加载完成后获取用户列表
        document.addEventListener('DOMContentLoaded', function() {
            loadUsers();
            setupFormValidation();
        });

        // 设置表单验证
        function setupFormValidation() {
            const forms = document.querySelectorAll('.needs-validation');
            Array.from(forms).forEach(form => {
                form.addEventListener('submit', event => {
                    if (!form.checkValidity()) {
                        event.preventDefault();
                        event.stopPropagation();
                    }
                    form.classList.add('was-validated');
                }, false);
            });
        }

        // 加载用户列表
        function loadUsers() {
            fetch('/user/list')
                .then(response => response.json())
                .then(users => {
                    const tbody = document.getElementById('userTableBody');
                    tbody.innerHTML = '';
                    users.forEach(user => {
                        tbody.innerHTML += `
                            <tr>
                                <td>${user.id}</td>
                                <td>${user.username}</td>
                                <td>${user.realName || '-'}</td>
                                <td>${user.email || '-'}</td>
                                <td>${user.phone || '-'}</td>
                                <td>${formatDate(user.createTime)}</td>
                                <td class="text-center table-actions">
                                    <button class="btn btn-sm btn-outline-warning me-2" onclick="editUser(${JSON.stringify(user).replace(/"/g, '&quot;')})">
                                        <i class="bi bi-pencil"></i> 编辑
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger" onclick="deleteUser(${user.id})">
                                        <i class="bi bi-trash"></i> 删除
                                    </button>
                                </td>
                            </tr>
                        `;
                    });
                })
                .catch(error => showToast('加载用户列表失败：' + error, 'danger'));
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '-';
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 添加用户
        function addUser() {
            const form = document.getElementById('addUserForm');
            if (!form.checkValidity()) {
                form.classList.add('was-validated');
                return;
            }

            const formData = new FormData(form);
            const user = Object.fromEntries(formData.entries());

            fetch('/user/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(user)
            })
            .then(response => response.text())
            .then(result => {
                if (result === 'success') {
                    showToast('添加成功', 'success');
                    bootstrap.Modal.getInstance(document.getElementById('addUserModal')).hide();
                    form.reset();
                    form.classList.remove('was-validated');
                    loadUsers();
                } else {
                    showToast('添加失败', 'danger');
                }
            })
            .catch(error => showToast('添加用户失败：' + error, 'danger'));
        }

        // 编辑用户
        function editUser(user) {
            const form = document.getElementById('editUserForm');
            form.id.value = user.id;
            form.username.value = user.username;
            form.realName.value = user.realName || '';
            form.email.value = user.email || '';
            form.phone.value = user.phone || '';
            
            new bootstrap.Modal(document.getElementById('editUserModal')).show();
        }

        // 更新用户
        function updateUser() {
            const form = document.getElementById('editUserForm');
            if (!form.checkValidity()) {
                form.classList.add('was-validated');
                return;
            }

            const formData = new FormData(form);
            const user = Object.fromEntries(formData.entries());

            fetch('/user/edit', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(user)
            })
            .then(response => response.text())
            .then(result => {
                if (result === 'success') {
                    showToast('更新成功', 'success');
                    bootstrap.Modal.getInstance(document.getElementById('editUserModal')).hide();
                    form.classList.remove('was-validated');
                    loadUsers();
                } else {
                    showToast('更新失败', 'danger');
                }
            })
            .catch(error => showToast('更新用户失败：' + error, 'danger'));
        }

        // 删除用户
        function deleteUser(id) {
            if (confirm('确定要删除这个用户吗？此操作不可恢复！')) {
                fetch(`/user/delete/${id}`, {
                    method: 'POST'
                })
                .then(response => response.text())
                .then(result => {
                    if (result === 'success') {
                        showToast('删除成功', 'success');
                        loadUsers();
                    } else {
                        showToast('删除失败', 'danger');
                    }
                })
                .catch(error => showToast('删除用户失败：' + error, 'danger'));
            }
        }

        // 搜索用户
        function searchUsers() {
            const keyword = document.getElementById('searchInput').value;
            fetch(`/user/search?keyword=${encodeURIComponent(keyword)}`)
                .then(response => response.json())
                .then(users => {
                    const tbody = document.getElementById('userTableBody');
                    tbody.innerHTML = '';
                    if (users.length === 0) {
                        tbody.innerHTML = `
                            <tr>
                                <td colspan="7" class="text-center">未找到匹配的用户</td>
                            </tr>
                        `;
                        return;
                    }
                    users.forEach(user => {
                        tbody.innerHTML += `
                            <tr>
                                <td>${user.id}</td>
                                <td>${user.username}</td>
                                <td>${user.realName || '-'}</td>
                                <td>${user.email || '-'}</td>
                                <td>${user.phone || '-'}</td>
                                <td>${formatDate(user.createTime)}</td>
                                <td class="text-center table-actions">
                                    <button class="btn btn-sm btn-outline-warning me-2" onclick="editUser(${JSON.stringify(user).replace(/"/g, '&quot;')})">
                                        <i class="bi bi-pencil"></i> 编辑
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger" onclick="deleteUser(${user.id})">
                                        <i class="bi bi-trash"></i> 删除
                                    </button>
                                </td>
                            </tr>
                        `;
                    });
                })
                .catch(error => showToast('搜索用户失败：' + error, 'danger'));
        }

        // 显示提示信息
        function showToast(message, type = 'info') {
            const toast = document.createElement('div');
            toast.className = `toast align-items-center text-white bg-${type} border-0 position-fixed top-0 end-0 m-3`;
            toast.setAttribute('role', 'alert');
            toast.setAttribute('aria-live', 'assertive');
            toast.setAttribute('aria-atomic', 'true');
            
            toast.innerHTML = `
                <div class="d-flex">
                    <div class="toast-body">
                        ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                </div>
            `;
            
            document.body.appendChild(toast);
            const bsToast = new bootstrap.Toast(toast);
            bsToast.show();
            
            toast.addEventListener('hidden.bs.toast', () => {
                toast.remove();
            });
        }

        // 回车键触发搜索
        document.getElementById('searchInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchUsers();
            }
        });
    </script>
</body>
</html> 